var Q = require("q");
var entityCollection = require('../../../Base/server/controllers/EntityCollection');
var completePlanController = require('../../../ProduceWork/server/controllers/CompletePlan.server.controllers');

//开工
exports.syncCompletePlanStart = function(req, res) {
	find(req, res).then(insertOrUpdate).catch(function(err) {
		res.json({
			Error: err
		});
	}).done();
};

//核准
exports.syncCompletePlanApprove = function(req, res) {
	find(req, res).then(deleteMO).catch(function(err) {
		res.json({
			Error: err
		});
	}).done();
};

//终止
exports.syncCompletePlanCancel = function(req, res) {
	find(req, res).then(cancelMO).catch(function(err) {
		res.json({
			Error: err
		});
	}).done();
};
//获取完工计划
exports.getCompletePlanByDate = function (req, res) {
    var completeDate = req.body.CompleteDate;
    console.log(completeDate);
    var resultData = []
    completePlanController.getCompletePlanByDate(completeDate, function (err, result) {
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '完工计划查询失败';
                newErr.message = '未找到对应的完工计划！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
            	for (var i = 0; i < result.length; i++) {
            		var completeQty = 0;
            		var r = result[i];
            		if(r.CompleteQty){
            			completeQty =  r.CompleteQty;
            		}
            		else{
                        completeQty = 0;
            		}
            		resultData.push({
						_id: r._id,
						Code: r.Code,
						LotNumber: r.LotNumber,
						Qty: r.Qty,
						CompleteQty: completeQty,
						QtyRate: completeQty/r.Qty*100,
						CompleteTime: r.CompleteTime,
						ItemMasterCode: r.ItemMaster.Code,
						Remark: r.Remark,
            		});
            	}
                res.json({
                    Data: resultData,
                    Error: null
                });
            }
        }
    });
};

function find(req, res) {
	var deferred = Q.defer();
	var entityItem = entityCollection.getEntity("CompletePlan");
	var parameter = req.body;
	var ID = parameter.ID;
	entityItem.find({
		ErpId: ID
	}, null, null, function(err, records) {
		if (!err) {
			var params = {
				req: req,
				res: res,
				records: records
			};
			deferred.resolve(params);
		} else {
			deferred.reject(err);
		}
	});

	return deferred.promise;
};


function insertOrUpdate(result) {
	var deferred = Q.defer();
	var entityMO = entityCollection.getEntity("CompletePlan");
	var parameter = result.req.body;
	var ID = parameter.ID;
	var ItemMaster = parameter.ItemMaster;
	var entityItem = entityCollection.getEntity("ItemMaster");

	var record = {};
	if (result.records.length < 1) {
		record.Code = parameter.DocNo;
		record.LotNumber = "";
		if (parameter.DemandCode != undefined && parameter.DemandCode != null && parameter.DemandCode != "" && parameter.DemandCode.length > 0) {
			record.LotNumber = parameter.DemandCode;
		};
		if (parameter.Seiban != undefined && parameter.Seiban != null && parameter.Seiban != "" && parameter.Seiban.length > 0) {
			record.LotNumber = parameter.Seiban;
		};

		record.Qty = parameter.ProductQty;
		record.CompleteTime = parameter.CompleteDate;
		record.Status = 0;
		record.ErpId = ID;
		record.CompleteQty = 0;
		record.Remark = "";
		entityItem.find({
			ErpId: ItemMaster
		}, null, null, function(err, items) {
			if (err) {
				deferred.reject({
					Error: '输采系统查询料品失败'
				});
			} else {
				if (items.length < 1) {
					deferred.reject({
						Error: '输采系统查询料品失败'
					});
				} else {
					record.ItemMaster = items[0]._id;
					entityMO.insert(record, function(ierr) {
						if (ierr) {
							deferred.reject(ierr);
						} else {
							deferred.resolve(record);
							result.res.json({
								Error: ''
							});
						}
					});
				}
			}
		});

	} else if (result.records.length >= 1) {
		var oldCompleteQty = result.records[0].CompleteQty;
		if (parameter.ProductQty < oldCompleteQty) {
			deferred.reject({
				Error: '生产数量' + parameter.ProductQty + '小于已完工数量' + oldCompleteQty
			});
		} else {
			record.Qty = parameter.ProductQty;
			record.CompleteTime = parameter.CompleteDate;
			entityMO.updateByValue({
				ErpId: ID
			}, record, function(err, rcd) {
				if (err) {
					deferred.reject(err);
				} else {
					deferred.resolve(rcd);
					result.res.json({
						Error: ''
					});
				}
			});
		}
	};

	return deferred.promise;
};

function deleteMO(result) {
	var deferred = Q.defer();
	var entityMO = entityCollection.getEntity("CompletePlan");
	var parameter = result.req.body;
	var ID = parameter.ID;
	if (result.records.length < 1) {
		deferred.reject({
			Error: '数采系统中未找到对应完工计划'
		});
	} else {
		var entityBarcode = entityCollection.getEntity("BarcodeMaster");
		entityBarcode.find({
			CompletePlan: result.records[0]._id
		}, null, null, function(err, data) {
			if (err) {
				deferred.reject({
					Error: '输采系统查询条码主档失败'
				});
			} else {
				if (data != null && data.lenght > 0) {
					deferred.reject({
						Error: '工单在数采系统中已经做过批次绑定，无法执行此操作'
					});
				} else {
					//删除
					entityMO.deleteByCondition({
						ErpId: ID
					}, function(err) {
						if (err) {
							deferred.reject(err);
						} else {
							deferred.resolve();
							result.res.json({
								Error: ''
							});
						}
					});
				}
			}
		});
	}
	return deferred.promise;
};

function cancelMO(result) {
	var deferred = Q.defer();
	var entityMO = entityCollection.getEntity("CompletePlan");
	var parameter = result.req.body;
	var ID = parameter.ID;
	if (result.records.length < 1) {
		deferred.reject({
			Error: '输采系统中未找到对应完工计划'
		});
	} else {
		entityMO.updateByValue({
			ErpId: ID
		}, {
			Status: 2
		}, function(err, rcd) {
			if (err) {
				deferred.reject(err);
			} else {
				deferred.resolve(rcd);
				result.res.json({
					Error: ''
				});
			}
		});
	}
	return deferred.promise;
};